package com.iaiai.cobra.core.config.intercepter;

import com.iaiai.cobra.common.constant.ResultCode;
import com.iaiai.cobra.common.util.JsonUtil;
import com.iaiai.cobra.common.vo.ResultVo;
import com.iaiai.cobra.core.BaseController;
import com.iaiai.cobra.web.vo.OnlineVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

//登录拦截器
@Slf4j
@Component
public class LoginIntercepter extends BaseController implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        OnlineVo online = getOnline();
        if (online==null) {
            return jumpLogin(response);
        }
        return true;
    }

    //跳转到登录页
    private boolean jumpLogin(HttpServletResponse response) throws IOException {
        ResultVo result = new ResultVo();
        result.setCode(ResultCode.LOGIN.getValue());
        response.getWriter().write(JsonUtil.getInstance().serialize(result));
        return false;
    }

}
